package cn.iocoder.yudao.framework.common.exception;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalExceptionEnum;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.common.util.string.StrUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LifeFly on 2016-09-13.
 */
public class ApplicationException extends RuntimeException implements Serializable {

    private String code;

    private String desc;

    private List<String> attachments;

    public ApplicationException(String ee) {
        super();
        this.code = ee;
        this.desc = ee;
    }

    public ApplicationException(BaseExceptionEnum ee) {
        super();
        this.code = ee.getCode();
        this.desc = ee.getDesc();
    }

    public ApplicationException(String ee, Throwable cause) {
        super(cause);
        this.code = ee;
        this.desc = ee;
    }

    public ApplicationException(BaseExceptionEnum ee, Throwable cause) {
        super(cause);
        this.code = ee.getCode();
        this.desc = ee.getDesc();
    }

    public String getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }

    public List<String> getAttachments() {
        return attachments;
    }

    /**
     * 增加异常辅助信息
     */
    public ApplicationException addAttachment(String attachment) {
        if (this.attachments == null) {
            this.attachments = new ArrayList<>();
        }
        if (StrUtil.isBlank(attachment)) {
            return this;
        }
        this.attachments.add(attachment);
        return this;
    }

    @Override
    public String getMessage() {
        if (CollectionUtil.isEmpty(this.attachments)) {
            return StrUtils.useFirstIfNotNull(desc, code);
        } else if (StrUtil.isNotBlank(desc) && desc.contains("{}")) {
            return StrUtil.format(desc, attachments);
        } else {
            return StrUtils.useFirstIfNotNull(desc, code) + " " + JsonUtils.toJsonString(attachments);
        }
    }
}
